package inits

import (
	"fmt"
	"gorm.io/driver/mysql"
	"gorm.io/gorm"
	"service/basic/config"
	"service/basic/global"
	"service/internal/model"
	"sync"
)

var once sync.Once
var err error

func InitMysql() {
	once.Do(func() {
		mysqlConfig := config.Config.Mysql
		dsn := fmt.Sprintf("%s:%s@tcp(%s:%s)/%s?charset=utf8&parseTime=True",
			mysqlConfig.User,
			mysqlConfig.Password,
			mysqlConfig.Host,
			mysqlConfig.Port,
			mysqlConfig.Database)

		global.DB, err = gorm.Open(mysql.Open(dsn))
		if err != nil {
			panic(err)
		}
		fmt.Println("Mysql连接成功")

		err = global.DB.AutoMigrate(&model.User{},
			&model.Order{},
			&model.Goods{},
			&model.Rider{},
			&model.Merchant{},
			&model.Appointment{},
			&model.Comment{},
			&model.Address{},
			&model.Operate{})
		if err != nil {
			panic(err)
		}
		fmt.Println("数据表迁移成功")

		db, err := global.DB.DB()
		if err != nil {
			panic(err)
		}

		db.SetMaxIdleConns(10)
		db.SetMaxOpenConns(100)

	})
}
